﻿using System;
using System.Windows;
using Microsoft.VisualBasic.ApplicationServices;

namespace TestFramework
{

    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : SingleInstanceApplication
    {
        public App()
        {
            this.InitializeComponent();
        }
    }

    // Using VB bits to detect single instances and process accordingly:
    //  * OnStartup is fired when the first instance loads
    //  * OnStartupNextInstance is fired when the application is re-run again
    //    NOTE: it is redirected to this instance thanks to IsSingleInstance
    public class SingleInstanceManager : WindowsFormsApplicationBase
    {
        SingleInstanceApplication app;

        public SingleInstanceManager()
        {
            this.IsSingleInstance = true;
        }

        protected override bool OnStartup(Microsoft.VisualBasic.ApplicationServices.StartupEventArgs e)
        {
            var screen = new SplashScreen(@"Resources\splash.jpg");
            screen.Show(false);
            base.OnStartup(e);

            // First time app is launched
            app = new App();

            screen.Close(TimeSpan.FromSeconds(2));
            app.Run();
            return false;
        }

        protected override void OnStartupNextInstance(StartupNextInstanceEventArgs eventArgs)
        {
            // Subsequent launches
            base.OnStartupNextInstance(eventArgs);
            app.Activate();
        }

    }

    public class SingleInstanceApplication : Application
    {
        public void Activate()
        {
            // Reactivate application's main window
            this.MainWindow.Activate();
        }
    }
}
